package com.house.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.house.common.BaseContext;
import com.house.entity.Menu;
import com.house.entity.Role;
import com.house.entity.User;
import com.house.mapper.MenuMapper;
import com.house.service.MenuService;
import com.house.service.RoleService;
import com.house.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired

    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Override
    public int save(Menu menu) {
        return menuMapper.insert(menu);
    }

    @Override
    public int update(Menu menu) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getMenuId, menu.getMenuId());
        return menuMapper.update(menu, queryWrapper);
    }

    @Override
    public Menu getMenuByMenuId(int menuId) {
        return menuMapper.selectByMenuId(menuId);
    }

    @Override
    public List<Menu> getMenus() {
        return menuMapper.selectMens();
    }

    @Override
    public List<Menu> getMenusByRole() {
        User user = userService.selectUserById(BaseContext.getThreadUserId());
        Role role = roleService.getRoleMenuIdsByRoleId(user.getRoleId());
        String menuIds = role.getMenuIds();
        if ("".equals(menuIds)) {
            return null;
        }
        String[] menuIdArr = menuIds.split(",");
        List<String> menuIdList = new ArrayList<>(Arrays.asList(menuIdArr));
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Menu::getMenuId, menuIdList);
        queryWrapper.orderByAsc(Menu::getSort);
        return menuMapper.selectList(queryWrapper);
    }

    @Override
    public int delete(int menuId) {
        return menuMapper.delete(menuId);
    }
}
